// 全局变量
let appData = {
    links: [],
    categories: [],
    tags: [],
    filteredLinks: [],
    currentFilters: {
        category: null,
        tags: [],
        search: ''
    },
    sortBy: 'name',
    sortOrder: 'asc'
};

// 当前操作的链接ID
let currentLinkId = null;

// 获取网站信息
document.getElementById('fetchSiteInfo').addEventListener('click', async function() {
    const url = document.getElementById('linkUrl').value.trim();
    if (!url) {
        showToast('请输入网站URL', 'warning');
        return;
    }

    const button = this;
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 获取中...';
    button.disabled = true;

    try {
        const response = await fetch('/api/fetch-site-info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ url: url })
        });

        const data = await response.json();

        if (response.ok && data.title) {
            // 自动填充表单
            if (data.title && data.title !== '未知网站') {
                document.getElementById('linkName').value = data.title;
            }
            if (data.description) {
                document.getElementById('linkDescription').value = data.description;
            }
            if (data.icon) {
                document.getElementById('linkIcon').value = data.icon;
            }
            
            showToast('网站信息获取成功', 'success');
        } else {
            showToast(data.error || '无法获取网站信息', 'error');
        }
    } catch (error) {
        showToast('获取失败，请检查网络连接', 'error');
    } finally {
        button.innerHTML = originalText;
        button.disabled = false;
    }
});

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    loadData();
    setupEventListeners();
    setupModals();
});

// 加载数据
async function loadData() {
    try {
        const response = await fetch('/api/data');
        const data = await response.json();
        appData.links = data.links || [];
        appData.categories = data.categories || [];
        appData.tags = data.tags || [];
        
        renderLinks();
        renderFilters();
        updateCategorySelect();
        updateTagsSelect();
    } catch (error) {
        console.error('加载数据失败:', error);
        showToast('加载数据失败，请刷新页面重试', 'error');
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 搜索功能
    document.getElementById('globalSearch').addEventListener('input', debounce(handleSearch, 300));
    
    // 清除过滤器
    document.getElementById('clearFilters').addEventListener('click', clearFilters);
    

    
    // 保存链接
    document.getElementById('saveLink').addEventListener('click', saveLink);
    
    // 类型管理
    document.getElementById('addCategory').addEventListener('click', addCategory);
    document.getElementById('newCategory').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addCategory();
    });
    
    // 标签管理
    document.getElementById('addTag').addEventListener('click', addTag);
    document.getElementById('newTag').addEventListener('keypress', (e) => {
        if (e.key === 'Enter') addTag();
    });
    
    // 数据导入导出
    document.getElementById('exportData').addEventListener('click', exportData);
    document.getElementById('importData').addEventListener('click', () => document.getElementById('importFile').click());
    document.getElementById('importFile').addEventListener('change', importData);
    document.getElementById('updateAllLinks').addEventListener('click', updateAllLinks);
    document.getElementById('syncGit').addEventListener('click', syncGit);
    
    // 删除确认
    document.getElementById('confirmDelete').addEventListener('click', confirmDelete);
    
    // 模态框关闭时重置表单
    document.getElementById('addLinkModal').addEventListener('hidden.bs.modal', function () {
        document.getElementById('linkForm').reset();
        document.getElementById('linkId').value = '';
        document.getElementById('addLinkModalLabel').textContent = '添加新链接';
        document.getElementById('saveLink').textContent = '保存';
    });
}

// 设置模态框事件
function setupModals() {
    // 管理类型模态框
    const manageCategoriesModal = document.getElementById('manageCategoriesModal');
    manageCategoriesModal.addEventListener('show.bs.modal', renderCategoriesManage);
    
    // 管理标签模态框
    const manageTagsModal = document.getElementById('manageTagsModal');
    manageTagsModal.addEventListener('show.bs.modal', renderTagsManage);
}

// 显示提示信息
function showToast(message, type = 'info') {
    const toastContainer = document.getElementById('toastContainer') || createToastContainer();
    
    const toast = document.createElement('div');
    toast.className = `toast align-items-center text-white bg-${type === 'success' ? 'success' : type === 'error' ? 'danger' : type === 'warning' ? 'warning' : 'info'} border-0`;
    toast.setAttribute('role', 'alert');
    toast.innerHTML = `
        <div class="d-flex">
            <div class="toast-body">
                ${message}
            </div>
            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button>
        </div>
    `;
    
    toastContainer.appendChild(toast);
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
    
    toast.addEventListener('hidden.bs.toast', () => {
        toast.remove();
    });
}

// 创建Toast容器
function createToastContainer() {
    const container = document.createElement('div');
    container.id = 'toastContainer';
    container.className = 'toast-container position-fixed top-0 end-0 p-3';
    container.style.zIndex = '9999';
    document.body.appendChild(container);
    return container;
}

// 渲染链接列表 - 按网页类型分块展示
function renderLinks() {
    applyFilters();
    
    const container = document.getElementById('linksContainer');
    const emptyState = document.getElementById('emptyState');
    
    if (appData.filteredLinks.length === 0) {
        container.style.display = 'none';
        emptyState.style.display = 'block';
        return;
    }
    
    container.style.display = 'block';
    emptyState.style.display = 'none';
    
    container.innerHTML = '';
    
    // 按类别分组
    const groupedByCategory = {};
    appData.filteredLinks.forEach(link => {
        const category = link.category || '未分类';
        if (!groupedByCategory[category]) {
            groupedByCategory[category] = [];
        }
        groupedByCategory[category].push(link);
    });
    
    // 按类别顺序渲染（可以自定义类别顺序）
    const categoryOrder = ['AI', '工具', '社区', '资源', '导航', '未分类'];
    
    categoryOrder.forEach(category => {
        if (groupedByCategory[category] && groupedByCategory[category].length > 0) {
            // 创建类别标题和可折叠功能
            const categorySection = document.createElement('div');
            categorySection.className = 'mb-4';
            
            const categoryId = `category-${category.replace(/\s+/g, '-').toLowerCase()}`;
            
            categorySection.innerHTML = `
                <div class="d-flex justify-content-between align-items-center category-header" data-category="${category}" data-target="${categoryId}">
                    <h5 class="fw-bold text-primary mb-0">${category}</h5>
                    <i class="fas fa-chevron-up text-primary"></i>
                </div>
                <div class="category-content" id="${categoryId}">
                    <div class="row">
                        ${groupedByCategory[category].map(link => {
                        const col = document.createElement('div');
                        col.className = 'col-12 col-md-4 col-lg-3 col-xl-2 mb-3 px-2';
                        
                        const truncatedDescription = link.description ? 
                            (link.description.length > 100 ? link.description.substring(0, 100) + '...' : link.description) : 
                            '暂无描述';
                        
                        const tagsHtml = link.tags && link.tags.length > 0 ?
                link.tags.map(tag => `<span class="badge badge-tag" style="font-size: 0.75rem; padding: 0.25rem 0.5rem; margin-right: 0.25rem; margin-bottom: 0.25rem;">${tag}</span>`).join('') : '';
                        
                        // 生成图标HTML
                        const firstChar = link.name ? link.name.charAt(0).toUpperCase() : '?';
                        const hasIcon = link.icon && link.icon.trim() !== '';
                        const iconClass = hasIcon ? 'site-icon site-icon-image' : 'site-icon site-icon-default';
                        const iconHtml = hasIcon ? 
                            `<img src="${link.icon}" alt="${link.name}" onerror="this.onerror=null; this.parentElement.className='site-icon site-icon-default'; this.parentElement.innerHTML='${firstChar}'">` : 
                            firstChar;
                        
                        return `
                            <div class="col-12 col-md-4 col-lg-3 col-xl-2 mb-3 px-2">
                                <div class="card link-card" data-id="${link.id}">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-end">
                                            <button class="btn btn-sm btn-outline-primary edit-link" data-id="${link.id}" title="编辑">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger delete-link ms-1" data-id="${link.id}" title="删除">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <div class="d-flex align-items-center mb-2">
                                            <div class="${iconClass} site-icon-sm">
                                                ${iconHtml}
                                            </div>
                                            <h6 class="card-title mb-0 small ms-2">${highlightSearch(link.name)}</h6>
                                        </div>
                                        <p class="link-url text-truncate">${link.url}</p>
                                        <p class="card-text">${highlightSearch(truncatedDescription)}</p>
                        ${link.category ? `<span class="badge filter-btn" style="font-size: 0.875rem; padding: 0.375rem 0.75rem; margin-bottom: 0.25rem; cursor: default; border-radius: var(--border-radius);">${link.category}</span>` : ''}
                        <div class="mt-1">${tagsHtml}</div>
                                    </div>
                                </div>
                            </div>
                        `;
                    }).join('')}
                </div>
            `;
            
            container.appendChild(categorySection);
            
            // 添加类别折叠事件
            const categoryHeader = categorySection.querySelector('.category-header');
            categoryHeader.addEventListener('click', function() {
                const targetId = this.getAttribute('data-target');
                const content = document.getElementById(targetId);
                const icon = this.querySelector('i');
                
                if (content.classList.contains('collapsed')) {
                    content.classList.remove('collapsed');
                    this.classList.remove('collapsed');
                    icon.className = 'fas fa-chevron-up text-primary';
                } else {
                    content.classList.add('collapsed');
                    this.classList.add('collapsed');
                    icon.className = 'fas fa-chevron-down text-primary';
                }
            });
            
            // 为刚添加的卡片绑定事件
            const cards = categorySection.querySelectorAll('.link-card');
            cards.forEach(card => {
                const linkId = card.getAttribute('data-id');
                const link = groupedByCategory[category].find(l => l.id == linkId);
                
                if (link) {
                    // 卡片主体点击事件（跳转到网站）
                    card.querySelector('.card-body').addEventListener('click', function(e) {
                        window.open(link.url, '_blank');
                    });
                    
                    // 编辑按钮事件
                    const editBtn = card.querySelector('.edit-link');
                    editBtn.addEventListener('click', function(e) {
                        e.stopPropagation();
                        editLink(link.id);
                    });
                    
                    // 删除按钮事件
                    const deleteBtn = card.querySelector('.delete-link');
                    deleteBtn.addEventListener('click', function(e) {
                        e.stopPropagation();
                        deleteLink(link.id);
                    });
                }
            });
        }
    });
}



// 渲染过滤器
function renderFilters() {
    // 渲染类型过滤器
    const categoriesContainer = document.getElementById('categoriesList');
    categoriesContainer.innerHTML = '';
    
    appData.categories.forEach(category => {
        const btn = document.createElement('button');
        btn.className = 'btn btn-sm filter-btn';
        btn.textContent = category;
        btn.dataset.category = category;
        
        if (appData.currentFilters.category === category) {
            btn.classList.add('active');
        }
        
        btn.addEventListener('click', () => filterByCategory(category));
        categoriesContainer.appendChild(btn);
    });
    
    // 渲染标签过滤器
    const tagsContainer = document.getElementById('tagsList');
    tagsContainer.innerHTML = '';
    
    appData.tags.forEach(tag => {
        const badge = document.createElement('span');
        badge.className = 'badge badge-tag';
        badge.textContent = tag;
        badge.style.cursor = 'pointer';
        
        if (appData.currentFilters.tags.includes(tag)) {
            badge.style.backgroundColor = 'var(--primary-color)';
            badge.style.color = 'white';
        }
        
        badge.addEventListener('click', () => filterByTag(tag));
        tagsContainer.appendChild(badge);
    });
}

// 应用过滤器
function applyFilters() {
    let filtered = [...appData.links];
    
    // 按类型过滤
    if (appData.currentFilters.category) {
        filtered = filtered.filter(link => link.category === appData.currentFilters.category);
    }
    
    // 按标签过滤
    if (appData.currentFilters.tags.length > 0) {
        filtered = filtered.filter(link => 
            link.tags && appData.currentFilters.tags.every(tag => link.tags.includes(tag))
        );
    }
    
    // 搜索过滤
    if (appData.currentFilters.search) {
        const searchTerm = appData.currentFilters.search.toLowerCase();
        filtered = filtered.filter(link => 
            link.name.toLowerCase().includes(searchTerm) ||
            link.description.toLowerCase().includes(searchTerm) ||
            (link.category && link.category.toLowerCase().includes(searchTerm)) ||
            (link.tags && link.tags.some(tag => tag.toLowerCase().includes(searchTerm)))
        );
    }
    
    
    
    appData.filteredLinks = filtered;
}

// 过滤功能
function filterByCategory(category) {
    if (appData.currentFilters.category === category) {
        appData.currentFilters.category = null;
    } else {
        appData.currentFilters.category = category;
    }
    renderLinks();
    renderFilters();
}

function filterByTag(tag) {
    const index = appData.currentFilters.tags.indexOf(tag);
    if (index > -1) {
        appData.currentFilters.tags.splice(index, 1);
    } else {
        appData.currentFilters.tags.push(tag);
    }
    renderLinks();
    renderFilters();
}

function handleSearch(event) {
    appData.currentFilters.search = event.target.value;
    renderLinks();
}

function clearFilters() {
    appData.currentFilters = {
        category: null,
        tags: [],
        search: ''
    };
    document.getElementById('globalSearch').value = '';
    renderLinks();
    renderFilters();
}



// 保存链接
async function saveLink() {
    // 获取选中的标签
    const tagsSelect = document.getElementById('linkTags');
    const selectedTags = Array.from(tagsSelect.selectedOptions).map(option => option.value);
    
    const formData = {
        name: document.getElementById('linkName').value.trim(),
        url: document.getElementById('linkUrl').value.trim(),
        description: document.getElementById('linkDescription').value.trim(),
        category: document.getElementById('linkCategory').value,
        icon: document.getElementById('linkIcon').value.trim(),
        tags: selectedTags
    };
    
    if (!formData.name || !formData.url) {
        showToast('请填写必填字段', 'error');
        return;
    }
    
    try {
        const linkId = document.getElementById('linkId').value;
        let response;
        
        if (linkId) {
            // 编辑模式
            response = await fetch(`/api/links/${linkId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
        } else {
            // 添加模式
            response = await fetch('/api/links', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(formData)
            });
        }
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            bootstrap.Modal.getInstance(document.getElementById('addLinkModal')).hide();
            showToast(linkId ? '链接更新成功' : '链接添加成功');
            
            // 恢复标题为添加模式
            document.getElementById('addLinkModalLabel').textContent = '添加新链接';
        } else {
            showToast(result.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('保存链接失败:', error);
        showToast('保存失败，请重试', 'error');
    }
}

// 编辑链接
function editLink(linkId) {
    console.log('编辑链接ID:', linkId);
    console.log('当前链接数据:', appData.links);
    
    const link = appData.links.find(l => l.id === linkId);
    if (!link) {
        console.error('未找到链接:', linkId);
        console.error('可用链接ID:', appData.links.map(l => l.id));
        return;
    }
    
    console.log('找到链接数据:', link);
    console.log('链接名称:', link.name);
    console.log('链接URL:', link.url);
    
    // 强制设置编辑模式
    document.getElementById('linkId').value = link.id;
    document.getElementById('linkName').value = link.name || '';
    document.getElementById('linkIcon').value = link.icon || '';
    document.getElementById('linkUrl').value = link.url || '';
    document.getElementById('linkDescription').value = link.description || '';
    document.getElementById('linkCategory').value = link.category || '';
    // 更新标签下拉框并设置已选中的标签
    updateTagsSelect(link.tags || []);
    
    // 设置标题和按钮文本
    document.getElementById('addLinkModalLabel').textContent = '编辑链接';
    document.getElementById('saveLink').textContent = '更新';
    
    // 验证表单填充
    console.log('表单填充完成:', {
        linkId: document.getElementById('linkId').value,
        linkName: document.getElementById('linkName').value,
        linkUrl: document.getElementById('linkUrl').value
    });
    
    const modal = new bootstrap.Modal(document.getElementById('addLinkModal'));
    modal.show();
    
    console.log('模态框已显示，数据已填充');
}

// 删除链接
function deleteLink(linkId) {
    currentLinkId = linkId;
    const modal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    modal.show();
}

async function confirmDelete() {
    if (!currentLinkId) return;
    
    try {
        const response = await fetch(`/api/links/${currentLinkId}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            bootstrap.Modal.getInstance(document.getElementById('deleteConfirmModal')).hide();
            showToast('链接删除成功');
        } else {
            showToast('删除失败', 'error');
        }
    } catch (error) {
        console.error('删除链接失败:', error);
        showToast('删除失败，请重试', 'error');
    }
    
    currentLinkId = null;
}

// 类型管理
async function addCategory() {
    const input = document.getElementById('newCategory');
    const name = input.value.trim();
    
    if (!name) return;
    
    try {
        const response = await fetch('/api/categories', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name })
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            input.value = '';
            renderCategoriesManage();
            updateCategorySelect();
            showToast('类型添加成功');
        } else {
            showToast('类型已存在', 'error');
        }
    } catch (error) {
        console.error('添加类型失败:', error);
        showToast('添加失败，请重试', 'error');
    }
}

async function deleteCategory(category) {
    if (!confirm(`确定要删除类型 "${category}" 吗？`)) return;
    
    try {
        const response = await fetch(`/api/categories/${encodeURIComponent(category)}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            renderCategoriesManage();
            updateCategorySelect();
            showToast('类型删除成功');
        } else {
            showToast(result.message || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除类型失败:', error);
        showToast('删除失败，请重试', 'error');
    }
}

async function updateCategory(oldName, newName) {
    if (!newName.trim() || oldName === newName) return;
    
    try {
        const response = await fetch(`/api/categories/${encodeURIComponent(oldName)}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: newName.trim() })
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            renderCategoriesManage();
            updateCategorySelect();
            showToast('类型更新成功');
        } else {
            showToast('类型已存在', 'error');
        }
    } catch (error) {
        console.error('更新类型失败:', error);
        showToast('更新失败，请重试', 'error');
    }
}

function renderCategoriesManage() {
    const container = document.getElementById('categoriesListManage');
    container.innerHTML = '';
    
    appData.categories.forEach(category => {
        const item = document.createElement('div');
        item.className = 'manage-item';
        item.innerHTML = `
            <span>${category}</span>
            <div>
                <button class="btn btn-sm btn-outline-primary edit-category" data-category="${category}" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger delete-category" data-category="${category}" title="删除">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
        
        item.querySelector('.edit-category').addEventListener('click', function() {
            const newName = prompt('请输入新的类型名称:', category);
            if (newName) updateCategory(category, newName);
        });
        
        item.querySelector('.delete-category').addEventListener('click', function() {
            deleteCategory(category);
        });
        
        container.appendChild(item);
    });
}

// 标签管理
async function addTag() {
    const input = document.getElementById('newTag');
    const name = input.value.trim();
    
    if (!name) return;
    
    try {
        const response = await fetch('/api/tags', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name })
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            input.value = '';
            renderTagsManage();
            showToast('标签添加成功');
        } else {
            showToast('标签已存在', 'error');
        }
    } catch (error) {
        console.error('添加标签失败:', error);
        showToast('添加失败，请重试', 'error');
    }
}

async function deleteTag(tag) {
    if (!confirm(`确定要删除标签 "${tag}" 吗？`)) return;
    
    try {
        const response = await fetch(`/api/tags/${encodeURIComponent(tag)}`, {
            method: 'DELETE'
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            renderTagsManage();
            showToast('标签删除成功');
        } else {
            showToast('删除失败', 'error');
        }
    } catch (error) {
        console.error('删除标签失败:', error);
        showToast('删除失败，请重试', 'error');
    }
}

async function updateTag(oldName, newName) {
    if (!newName.trim() || oldName === newName) return;
    
    try {
        const response = await fetch(`/api/tags/${encodeURIComponent(oldName)}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: newName.trim() })
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            renderTagsManage();
            showToast('标签更新成功');
        } else {
            showToast('标签已存在', 'error');
        }
    } catch (error) {
        console.error('更新标签失败:', error);
        showToast('更新失败，请重试', 'error');
    }
}

function renderTagsManage() {
    const container = document.getElementById('tagsListManage');
    container.innerHTML = '';
    
    appData.tags.forEach(tag => {
        const item = document.createElement('div');
        item.className = 'manage-item';
        item.innerHTML = `
            <span>${tag}</span>
            <div>
                <button class="btn btn-sm btn-outline-primary edit-tag" data-tag="${tag}" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger delete-tag" data-tag="${tag}" title="删除">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        `;
        
        item.querySelector('.edit-tag').addEventListener('click', function() {
            const newName = prompt('请输入新的标签名称:', tag);
            if (newName) updateTag(tag, newName);
        });
        
        item.querySelector('.delete-tag').addEventListener('click', function() {
            deleteTag(tag);
        });
        
        container.appendChild(item);
    });
}

// 更新分类下拉框
function updateCategorySelect() {
    const select = document.getElementById('linkCategory');
    if (!select) {
        console.error('找不到linkCategory元素');
        return;
    }
    
    const currentValue = select.value;
    
    console.log('更新类型下拉框，当前类型:', appData.categories);
    
    select.innerHTML = '<option value="">选择类型...</option>';
    appData.categories.forEach(category => {
        const option = document.createElement('option');
        option.value = category;
        option.textContent = category;
        select.appendChild(option);
    });
    
    select.value = currentValue;
    console.log('类型下拉框已更新，选项数量:', appData.categories.length);
}

// 更新标签下拉框
function updateTagsSelect(selectedTags = []) {
    const select = document.getElementById('linkTags');
    if (!select) {
        console.error('找不到linkTags元素');
        return;
    }
    
    select.innerHTML = '';
    appData.tags.forEach(tag => {
        const option = document.createElement('option');
        option.value = tag;
        option.textContent = tag;
        // 设置已选中的标签
        if (selectedTags.includes(tag)) {
            option.selected = true;
        }
        select.appendChild(option);
    });
    
    // 为select添加事件监听器，优化选中项的显示
    select.addEventListener('change', showSelectedTagsSummary);
    
    // 初始化时显示选中项摘要
    showSelectedTagsSummary.call(select);
    
    console.log('标签下拉框已更新，选项数量:', appData.tags.length);
}

// 显示选中标签的摘要信息
function showSelectedTagsSummary() {
    const select = this;
    const selectedOptions = Array.from(select.selectedOptions);
    const selectedCount = selectedOptions.length;
    
    // 确保select元素有title属性显示选中项
    if (selectedCount > 0) {
        // 如果选中项不多，直接显示它们的文本
        if (selectedCount <= 3) {
            select.title = selectedOptions.map(option => option.textContent).join(', ');
        } else {
            // 如果选中项太多，显示选中数量
            select.title = `已选择 ${selectedCount} 个标签`;
        }
    } else {
        select.title = '请选择标签';
    }
}

// 数据导入导出
async function exportData() {
    try {
        const response = await fetch('/api/export');
        const data = await response.json();
        
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `linkhub-backup-${new Date().toISOString().split('T')[0]}.json`;
        a.click();
        URL.revokeObjectURL(url);
        
        showToast('数据导出成功');
    } catch (error) {
        console.error('导出数据失败:', error);
        showToast('导出失败，请重试', 'error');
    }
}

async function importData(event) {
    const file = event.target.files[0];
    if (!file) return;
    
    try {
        const text = await file.text();
        const data = JSON.parse(text);
        
        const response = await fetch('/api/import', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (result.success) {
            await loadData();
            showToast('数据导入成功');
        } else {
            showToast(result.message || '导入失败', 'error');
        }
    } catch (error) {
        console.error('导入数据失败:', error);
        showToast('导入失败，请检查文件格式', 'error');
    }
    
    event.target.value = '';
}

// 一键更新所有链接信息
async function updateAllLinks() {
    if (!appData.links || appData.links.length === 0) {
        showToast('暂无链接可更新', 'warning');
        return;
    }

    const confirmUpdate = confirm(`确定要更新所有 ${appData.links.length} 个链接的信息吗？\n\n这将：\n• 获取每个网站的最新名称、描述和图标\n• 可能需要一些时间\n• 无法撤销此操作`);
    
    if (!confirmUpdate) return;

    const button = document.getElementById('updateAllLinks');
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 更新中...';
    button.disabled = true;

    let successCount = 0;
    let failCount = 0;
    let skipCount = 0;

    // 显示进度条
    const progressToast = document.createElement('div');
    progressToast.className = 'toast show position-fixed top-0 start-50 translate-middle-x mt-3';
    progressToast.style.zIndex = '9999';
    progressToast.innerHTML = `
        <div class="toast-header">
            <strong class="me-auto">更新进度</strong>
            <small id="progressText">0/${appData.links.length}</small>
        </div>
        <div class="toast-body">
            <div class="progress">
                <div class="progress-bar" role="progressbar" style="width: 0%" id="progressBar"></div>
            </div>
            <small class="text-muted mt-1 d-block" id="progressDetail">准备中...</small>
        </div>
    `;
    document.body.appendChild(progressToast);

    try {
        for (let i = 0; i < appData.links.length; i++) {
            const link = appData.links[i];
            const progress = ((i + 1) / appData.links.length) * 100;
            
            document.getElementById('progressText').textContent = `${i + 1}/${appData.links.length}`;
            document.getElementById('progressBar').style.width = `${progress}%`;
            document.getElementById('progressDetail').textContent = `正在更新: ${link.name}`;

            try {
                const response = await fetch('/api/fetch-site-info', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ url: link.url })
                });

                const data = await response.json();

                if (response.ok && data.title) {
                    // 更新链接信息
                    const updatedLink = {
                        ...link,
                        name: data.title && data.title !== '未知网站' ? data.title : link.name,
                        description: data.description || link.description,
                        icon: data.icon || link.icon
                    };

                    // 保存更新后的链接
                    const saveResponse = await fetch(`/api/links/${link.id}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(updatedLink)
                    });

                    if (saveResponse.ok) {
                        successCount++;
                    } else {
                        failCount++;
                    }
                } else {
                    skipCount++;
                }
            } catch (error) {
                console.error(`更新 ${link.name} 失败:`, error);
                failCount++;
            }

            // 添加短暂延迟避免请求过快
            await new Promise(resolve => setTimeout(resolve, 1000));
        }

        // 移除进度条
        document.body.removeChild(progressToast);

        // 显示结果
        showToast(`更新完成！成功: ${successCount}, 失败: ${failCount}, 跳过: ${skipCount}`, 
                 failCount > 0 ? 'warning' : 'success');

        // 重新加载数据
        await loadData();

    } catch (error) {
        console.error('一键更新失败:', error);
        showToast('更新过程中出现错误', 'error');
        
        // 确保移除进度条
        if (document.body.contains(progressToast)) {
            document.body.removeChild(progressToast);
        }
    } finally {
        button.innerHTML = originalText;
        button.disabled = false;
    }
}

// 同步Git仓库
async function syncGit() {
    const confirmSync = confirm('确定要同步Git仓库吗？\n\n这将：\n• 添加所有更改\n• 提交更改\n• 拉取远程更改\n• 推送到远程仓库');
    
    if (!confirmSync) return;

    const button = document.getElementById('syncGit');
    const originalText = button.innerHTML;
    button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 同步中...';
    button.disabled = true;

    try {
        const response = await fetch('/api/sync-git', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ message: '同步数据文件', branch: 'master' })
        });

        const data = await response.json();

        if (data.success) {
            showToast('Git同步成功', 'success');
        } else {
            showToast(`同步失败: ${data.message}`, 'error');
        }
    } catch (error) {
        console.error('Git同步失败:', error);
        showToast('同步过程中出现错误', 'error');
    } finally {
        button.innerHTML = originalText;
        button.disabled = false;
    }
}

// 清除表单
function clearLinkForm() {
    document.getElementById('linkForm').reset();
    document.getElementById('linkId').value = '';
}

function showToast(message, type = 'success') {
    const toast = document.getElementById('liveToast');
    const toastMessage = document.getElementById('toastMessage');
    const toastIcon = toast.querySelector('i');
    
    toastMessage.textContent = message;
    
    // 设置图标
    if (type === 'error') {
        toastIcon.className = 'fas fa-exclamation-circle text-danger me-2';
    } else {
        toastIcon.className = 'fas fa-check-circle text-success me-2';
    }
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

function highlightSearch(text) {
    const searchTerm = appData.currentFilters.search;
    if (!searchTerm) return text;
    
    const regex = new RegExp(`(${searchTerm})`, 'gi');
    return text.replace(regex, '<span class="search-highlight">$1</span>');
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}